import Vue from 'vue'
import Vuex from 'vuex'
import {
    getUser
} from "@/api/user"

Vue.use(Vuex)

const USER_KEY = "USERINFO"

function getSession() {
    let o = null;
    try {
        o = JSON.parse(sessionStorage.getItem(USER_KEY));
    } catch (error) {
        o = {};
    }
    if (!o) {
        o = {};
    }
    return o;
}

function setSession(data) {
    sessionStorage.setItem(
        USER_KEY,
        JSON.stringify(data)
    );
}

const userInfo = getSession();

const store = new Vuex.Store({
    state: {
        loading: true,
        user: {}
    },
    getters: {
        // 获取用户信息
        GetUserInfo: (state) => {
            return state.user
        },
        GetLoading: (state) => {
            return state.loading
        }
    },
    mutations: {
        SET_USER: (state, user) => {
            state.user = user
        },
    },
    actions: {
        // 获取用户信息
        GetUserInfo({
            commit
        }) {
            return new Promise((resolve, reject) => {
                // session中没有数据
                if (userInfo.id == undefined) {
                    if (localStorage.getItem("UID") != null) {
                        console.log("send")
                        getUser(localStorage.getItem("UID")).then(res => {
                            console.log(res);
                            // 保存到session
                            setSession(res)
                            setUserInfo(res, commit)
                            resolve(res)
                        }).catch(error => {
                            reject(error)
                        }).finally(() => {
                            store.state.loading = false
                        })
                    }
                } else {
                    console.log("getsession")
                    setUserInfo(userInfo, commit)
                    // setTimeout(() => {
                    //     store.state.loading = false
                    // }, 2000);
                    store.state.loading = false
                }
            })
        },
        // 保存(更新)用户信息
        SaveUserInfo({
            commit
        }, ) {
            return new Promise((resolve) => {
                getUser(localStorage.getItem("UID")).then(res => {
                    console.log(res);
                    // 保存到session
                    setSession(res)
                    setUserInfo(res, commit)
                    store.state.loading = false
                    resolve(res)
                })
            })
        },
    }
})
export const setUserInfo = (res, commit) => {
    commit('SET_USER', res)
}

store.dispatch("GetUserInfo");



export default store